import paramiko
from untils.untils import log
import time

class SSH(object):

    def __init__(self, server):

        self.des_login_user = server.username
        self.des_ip =  server.ip
        self.des_passwd =  server.password
        self.create_ssh()
        log('ssh to {}'.format(self.des_ip))

    def create_ssh(self):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self._connect()


    def _connect(self):
        self.ssh.connect(self.des_ip,22, self.des_login_user, self.des_passwd, timeout=5)

    def excute_cmd(self, cmd):
        
        stdin, stdout, stderr = self.ssh.exec_command(cmd)
        log('ssh to {} ,excute_cmd {}'.format(self.des_ip, cmd))
        log('excute_cmd {}, return:({})'.format(cmd,stdout.read().decode('utf-8')))
        return  stdout.read().decode('utf-8')
               
    def close(self):
        self.ssh.close()

ZONE = {
    'Shanghai': '/usr/share/zoneinfo/Asia/Shanghai',
    'Dhaka': '/usr/share/zoneinfo/Asia/Dhaka',
    'Rangoon': '/usr/share/zoneinfo/Asia/Rangoon',
    'Singapore': '/usr/share/zoneinfo/Asia/Singapore',  
}

class Sync_Remote(SSH):
    
    def cat(self,path ):
        return self.excute_cmd('cat {0}'.format(path))

    def time_sync_from(self, ntp_server, timeZone):
        self.excute_cmd('/usr/sbin/ntpdate {0}'.format(ntp_server))
        self.excute_cmd('/usr/sbin/sntp -P no -r {0}'.format(ntp_server))
        self.write_ntp_sync_task_2_root_crontab_from_NTP(ntp_server)
        self.ln_localtime_file(timeZone)
        self.restart_service('cron')
        self.excute_cmd('hwclock -w')

    def ln_localtime_file(self, zone=None):
        path = ZONE.get(zone)
        if path is not None:
            self.excute_cmd('/bin/bash -c "ln -sf {0} /etc/localtime"'.format(path))

    def stop_service(self, cmd):
        return self.excute_cmd('service {0} stop'.format(cmd))

    def start_service(self, cmd):
        return self.excute_cmd('service {0} start'.format(cmd))

    def restart_service(self, cmd):
        a = self.stop_service(cmd)
        b = self.start_service(cmd)
        return a + b

    def root_crontab(self):
        return self.excute_cmd('crontab -l')

    def echo_to_root_crontab(self, cmd):
        self.excute_cmd('/bin/bash -c "crontab -l > /tmp/crontab.bak"')
        return self.excute_cmd('/bin/bash -c "echo {0} >> /tmp/crontab.bak"'.format(cmd))

    def write_ntp_sync_task_2_root_crontab_from_NTP(self, ntp):
        cmd1 = "'*/1 * * * * /usr/sbin/sntp -P no -r {server}'".format(server=ntp)
        cmd2 = "'*/1 * * * * /usr/sbin/ntpdate {server}'".format(server=ntp)
        cmd = [cmd1, cmd2]
        root_crontab = self.root_crontab()
        need_reload = False
        self.cron_bak_file = '/tmp/crontab.bak.{}'.format(int(time.time()))
        self.excute_cmd('/bin/bash -c "crontab -l > {}"'.format(self.cron_bak_file))
        for c in cmd:
            if c not in root_crontab:
                need_reload = True
                self.excute_cmd('/bin/bash -c "echo {} >> {}"'.format(c, self.cron_bak_file))
        if need_reload:
            self.reload_crontab()

    def reload_crontab(self):
        return self.excute_cmd('crontab -u {} {}'.format(self.des_login_user,self.cron_bak_file))
